package com.example.service.impl;

import com.example.common.ResultCode;
import com.example.dao.MessageMapper;
import com.example.exception.ApplicationException;
import com.example.model.Message;
import com.example.model.User;
import com.example.service.IMessageService;
import com.example.service.IUserService;
import com.example.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-10-20
 * Time: 15:07
 */
@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private IUserService userService;


    /**
     * 创建站内信
     * @param message 站内信对象
     */
    @Override
    public void create(Message message) {
        //1.非空校验
        if(message == null || message.getPostUserId() == null || message.getReceiveUserId() == null
                || StringUtils.isEmpty(message.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.校验接收用户是否存在
        User user = userService.selectById(message.getReceiveUserId());
        if(user == null ||user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //3.设置站内信对象默认值
        message.setState((byte) 0);
        message.setDeleteState((byte) 0);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        //4.插入站内信信息到数据库中
        int insertCount = messageMapper.insertSelective(message);
        if(insertCount != 1){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new RuntimeException(ResultCode.FAILED_CREATE.toString());
        }
    }
    /**
     * 查询用户未读站内信数量
     * @param userId 用户id
     * @return 用户未读站内信数量
     */
    @Override
    public Integer selectUnreadCount(Long userId) {
        //1.非空校验
        if(userId == null || userId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.查询用户未读站内信数量
        Integer result = messageMapper.selectUnreadCount(userId);

        //3.返回结果
        return result;
    }
    /**
     * 根据用户id查询用户所有站内信
     * @param receiveUserId 接收用户id
     * @return 用户所有站内信
     */
    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        //1.非空校验
        if(receiveUserId == null || receiveUserId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.根据用户id查询用户所有站内信
        List<Message> result = messageMapper.selectByReceiveUserId(receiveUserId);
        return result;
    }
    /**
     * 修改站内信状态
     * @param id 站内信id
     * @param state 站内信状态
     */
    @Override
    public void updateStateById(Long id, Byte state) {
        //1.非空校验
        if(id == null || id <= 0 || state < 0 || state > 2){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.构造更新对象
        Message message = new Message();
        message.setId(id);
        message.setState(state);
        message.setUpdateTime(new Date());
        //3.修改站内信状态
        int updateCount = messageMapper.updateByPrimaryKeySelective(message);
        if(updateCount != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.ERROR_SERVICES.toString());
        }
    }
    /**
     * 根据id查询站内信
     * @param id 站内信id
     * @return 站内信对象
     */
    @Override
    public Message selectById(Long id) {
        //1.非空校验
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.根据id查询站内信
        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }
    /**
     * 回复站内信
     * @param repliedId 被回复的站内信id
     * @param message 站内信对象
     */
    @Override
    @Transactional
    public void reply(Long repliedId, Message message) {
        //1.非空校验
        if(repliedId == null || repliedId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2,校验被回复的站内信是否存在
        Message repliedMessage = messageMapper.selectByPrimaryKey(repliedId);
        if(repliedMessage == null || repliedMessage.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
        }
        //3.更新被回复的站内信状态为已回复，即2
        updateStateById(repliedId, (byte) 2);
        //4.将回复的内容写入数据库
        create(message);
    }
}
